package com.groupfour.attendancemanagementsystem.controller;

import com.groupfour.attendancemanagementsystem.entity.DO.*;
import com.groupfour.attendancemanagementsystem.entity.DTO.UserLoginDTO;
import com.groupfour.attendancemanagementsystem.entity.VO.UserLoginVO;
import com.groupfour.attendancemanagementsystem.service.AdminService;
import com.groupfour.attendancemanagementsystem.service.LoginService;
import com.groupfour.attendancemanagementsystem.service.StudentService;
import com.groupfour.attendancemanagementsystem.service.TeacherService;
import com.groupfour.attendancemanagementsystem.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private TeacherService teacherService;


    // 获取验证码图片
    @GetMapping(value = "/getVerifiCodeImage",produces = "image/jpeg")
//    @ResponseBody
    public void getVerifiCodeImage(HttpServletRequest request, HttpServletResponse response){
        // 获取图片
        BufferedImage verifiCodeImage = CreateVerifiCodeImage.getVerifiCodeImage();
        // 获取图片上的验证码
        String verifiCode =new String( CreateVerifiCodeImage.getVerifiCode());
        // 将验证码文本放入session域,为下一次验证做准备
        HttpSession session = request.getSession();
        session.setAttribute("verifiCode",verifiCode);

        // 将验证码图片响应给浏览器
        try {
            ImageIO.write(verifiCodeImage,"JPEG",response.getOutputStream());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/doLogin")
    public Object doLogin(@RequestBody UserLoginDTO userLoginDTO) {
            // 准备一个map用户存放响应的数据
            Map<String, Object> map = new LinkedHashMap<>();

            // 将页面输入密码进行加密处理，并存入DTO对象
            userLoginDTO.setUserPassword(MD5.encrypt(userLoginDTO.getUserPassword()));

            switch (userLoginDTO.getUserType()) {
                case 0:
                    try {
                        AdminDO admin = loginService.adminLogin(userLoginDTO);
                        if (null != admin) {
                            map.put("token", JwtHelper.createToken(admin.getAdminCode(), admin.getAdminPassword(), 0));
                            map.put("userName",admin.getAdminName());
                        } else {
                            throw new RuntimeException("用户名或者密码有误");
                        }
                        return Result.ok(map);
                    } catch (RuntimeException e) {
                        e.printStackTrace();
                        return Result.fail().message(e.getMessage());
                    }
                case 1:
                    try {
                        StudentDO student = loginService.studentLogin(userLoginDTO);
                        if (null != student) {
                            map.put("token", JwtHelper.createToken(student.getStudentCode(), student.getStudentPassword(), 1));
                            map.put("userName",student.getStudentName());
                        } else {
                            throw new RuntimeException("用户名或者密码有误");
                        }
                        return Result.ok(map);
                    } catch (RuntimeException e) {
                        e.printStackTrace();
                        return Result.fail().message(e.getMessage());
                    }
                case 2:
                    try {
                        TeacherDO teacher = loginService.teacherLogin(userLoginDTO);
                        if (null != teacher) {
                            map.put("token", JwtHelper.createToken(teacher.getTeacherCode(), teacher.getTeacherPassword(), 2));
                            map.put("userName",teacher.getTeacherName());
                        } else {
                            throw new RuntimeException("用户名或者密码有误");
                        }
                        return Result.ok(map);
                    } catch (RuntimeException e) {
                        e.printStackTrace();
                        return Result.fail().message(e.getMessage());
                    }
            }
            return Result.fail().message("查无此用户");
        }

    @GetMapping("/getUserInfo")
    @ResponseBody
    public Result getInfoByToken(@RequestHeader("token")String token){

        boolean expiration = JwtHelper.isExpiration(token);
        if (expiration) {
            return Result.build(null, ResultCodeEnum.TOKEN_ERROR);
        }
        //从token中解析出 用户账号和用户的类型
        String userCode = JwtHelper.getUserCode(token);
        Integer userType = JwtHelper.getUserType(token);


        Map<String,Object> map =new LinkedHashMap<>();
        switch (userType){
            case 0:
                AdminDO admin = adminService.getAdminByAdminCode(userCode);
                map.put("userType",0);
                map.put("user",admin);
                break;
            case 1:
                StudentDO student = studentService.getStudentByStudentCode(userCode);
                map.put("userType",1);
                map.put("user",student);
                break;
            case 2:
                TeacherDO teacher= teacherService.getTeacherByTeacherCode(userCode);
                map.put("userType",2);
                map.put("user",teacher);
                break;
        }
        return Result.ok(map);
    }

}
